package com.lbg.drug.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lbg.drug.dto.Admindto;
import com.lbg.drug.entity.Menu;
import com.lbg.drug.mapper.MenuMapper;
import com.lbg.drug.service.MenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lbg
 * @since 2022-04-27
 */
@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuMapper menuMapper;




    @Override
    public List<Menu> getMenu(HttpSession session) {
        Admindto admin = (Admindto) session.getAttribute("Admin");
        if ("普通用户".equals(admin.getUserType())){
            QueryWrapper<Menu> m = new QueryWrapper<>();
            m.eq("parent_id", "0").eq("user_type","普通用户") ;
            //父类菜单
            List<Menu> parents = menuMapper.selectList(m);

            for (Menu parent : parents) {
                List<Menu> childs = new ArrayList<>();
                for (Menu chlid : getchilds(admin.getUserType())) {
                    if (parent.getMenuId().equals(chlid.getParentId())) {
                        childs.add(chlid);
                    }
                }
                parent.setChilds(childs);
            }
            return parents;
        }else{
            QueryWrapper<Menu> m = new QueryWrapper<>();
            m.eq("parent_id", "0");
            //父类菜单
            List<Menu> parents = menuMapper.selectList(m);

            for (Menu parent : parents) {
                List<Menu> childs = new ArrayList<>();
                for (Menu chlid : getchilds(null)) {
                    if (parent.getMenuId().equals(chlid.getParentId())) {
                        childs.add(chlid);
                    }
                }
                parent.setChilds(childs);
            }
            return parents;
        }
        }


    /**
     * 子类菜单
     *
     * @return
     */
    private List<Menu> getchilds(String type) {
        if ("普通用户".equals(type)) {
            QueryWrapper<Menu> m = new QueryWrapper<>();
            m.ne("parent_id", "0").eq("user_type","普通用户");
            List<Menu> menus = menuMapper.selectList(m);
            return menus;
        }else {
            QueryWrapper<Menu> m = new QueryWrapper<>();
            m.ne("parent_id", "0");
            List<Menu> menus = menuMapper.selectList(m);
            return menus;
        }
    }
}
